package com.lovo;

import com.lovo.config.ApplicationConfig;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

public class ApplicationMain {
    public static void main(String[] args) throws Exception {

        // 实例化Tomcat
        Tomcat tomcat = new Tomcat();
        // 设置Tomcat端口        
        tomcat.setPort(8080);
        // 引导HTTP引擎        
        tomcat.getConnector();
        Context ctx = tomcat.addContext("", null);
        addFilter(ctx,"encodingFilter",
                new CharacterEncodingFilter("utf-8",true,true),
                "/*");
        WebApplicationContext applicationContext = createApplicationContext(ctx.getServletContext());
        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);

        // 第二个参数是Servlet名称        
        Wrapper servlet = Tomcat.addServlet(ctx, "dispatcherServlet", dispatcherServlet);
        // 启动初始化Servlet        
        servlet.setLoadOnStartup(1);
        // 任何访问路径都能进入该Servlet        
        servlet.addMapping("/*");
        // 启动服务器        
        tomcat.start();
    }

    public static WebApplicationContext createApplicationContext(ServletContext servletContext){
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(ApplicationConfig.class);
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();
        applicationContext.registerShutdownHook();
        return applicationContext;
    }

    public static void addFilter(Context context, String filterName, Filter filter, String urlPattern) {
        FilterDef filterDef = new FilterDef();
        filterDef.setFilter(filter);
        filterDef.setFilterName(filterName);
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName(filterName);
        filterMap.addURLPatternDecoded(urlPattern);
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);

    }


}
